import time
import logging
import os
import socket

from virtual_operator_service_base.utils.common_singleton import CommonSingleton

hostname = socket.gethostname()
current_directory = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath(os.path.dirname(current_directory) + os.path.sep + ".")
project_name = (root_path.split(os.path.sep))[-1]

formatter = logging.Formatter(
    fmt="%(asctime)s %(levelname)s %(filename)s %(funcName)s[line:%(lineno)d] %(message)s",
    datefmt="%Y-%m-%d %X"
)

log_base_path = "logs/virtual_operator_service_base/virtual_operator_service_base"


def get_current_time():
    current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))  # 返回当前时间
    return current_time


@CommonSingleton
class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }

    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super().__new__(cls)

        return cls.instance

    def __init__(self):
        self.current_time = get_current_time()
        filename = log_base_path + "-" + get_current_time() + '.log'
        self.logger = logging.getLogger(filename)
        self.format_str = formatter  # 设置日志格式
        self.create_handler()

    def create_handler(self):
        self.current_time = get_current_time()
        filename = log_base_path + "-" + get_current_time() + '.log'
        self.logger = logging.getLogger(filename)
        self.logger.setLevel(logging.INFO)
        sh = logging.StreamHandler()
        sh.setFormatter(self.format_str)
        th = logging.FileHandler(filename=filename, encoding='utf-8')
        th.setFormatter(self.format_str)
        self.logger.addHandler(sh)
        self.logger.addHandler(th)

    def info(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()

        self.logger.info(msg)
        return

    def warning(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()
        self.logger.warning(msg)
        return

    def error(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler()
        self.logger.error(msg)
        return


logger = Logger().logger
